<?php
define( '_JEXEC', 1 );
defined('_JEXEC') or die('Restricted access');
define( 'DS', DIRECTORY_SEPARATOR );
define('JPATH_BASE',dirname(__FILE__).DS."..".DS."..");
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
require_once ( JPATH_BASE .DS.'libraries'.DS.'loader.php' );
ini_set('memory_limit', '1024M'); 
//require_once ( dirname(__FILE__).DS.'qualifier.php' );

jimport( 'joomla.application.cli' );
jimport('joomla.database.database');
jimport( 'joomla.database.table' );

$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();
JPluginHelper::importPlugin('system');

$db =& JFactory::getDBO();
$user =& JFactory::getUser();
$user_id = $user->get('id');
//echo "<p>Your name is {$user->name}, your email is {$user->email}, and your username is {$user->username}</p>";
//echo "<p>Your usertype is {$user->usertype} which has a group id of {$user->gid}.</p>";

//$qr = new qualifierResult();

try {
    

	$fileName = $_POST["fileName"];
	
	echo "<p>Wczytany plik na serwerze: " . $fileName . "</p>";
	
	$file_handle = fopen(JPATH_BASE.DS."files".DS.$fileName, 'r');
	
	$pattern_file_handle = fopen(JPATH_BASE.DS."files".DS."pattern".DS."pattern_73XdaL54o77guF8285ovg27zwEJ301.txt", 'r');
	
	$rmse_sum = 0;
	$set_count = 0;
	$rmse = 0;
	
	while (!feof($file_handle) && !feof($pattern_file_handle) ) {
		$line = fgets($file_handle);
		$line_pattern = fgets($pattern_file_handle);
		
		if(strpos($line_pattern, ":") > 0) {} else {
			$parts = explode(',', $line);
			if(count($parts) < 2)
				continue;
			$rating = floatval(trim($parts[1]));
			$rating_pattern = floatval(trim($line_pattern));
			$rmse_sum += pow(($rating - $line_pattern), 2);
			$set_count++;
			unset($parts);
			unset($rating);
			unset($rating_pattern);
		//print $parts[0] . $parts[1]. "<BR>";
		}
	}
	
	
	if($rmse_sum > 0 && $set_count > 0) {
		$rmse = sqrt($rmse_sum / $set_count);
		$query = "INSERT INTO ".$db->nameQuote('#__putmovies_rating')." (`user_id`, `rmse`) VALUES (".$user_id.", ".$rmse.") ;";
		$db->setQuery($query);
		$dbResults = $db->query();
	}
	
	echo "<h3>RMSE = ".$rmse."</h3><p>Przeczytano ".$set_count." ocen użytkowników.</p><p>Wynik został zapisany na liście rankingowej.</p>";
	
	fclose($file_handle);
	fclose($pattern_file_handle);

	
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
exit();